﻿using Admin.Core.Common.Attributes;
using System;
using System.Collections.Generic;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;

namespace Admin.Core.Common.Helpers
{
    /// <summary>
    /// 邮件帮助
    /// </summary>
    [SingleInstance]
    public class EmailHelper
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="server">邮件服务器</param>
        /// <param name="port">端口</param>
        /// <param name="from">发件人</param>
        /// <param name="toEmail">收件人</param>
        /// <param name="subject">主题</param>
        /// <param name="message"></param>
        /// <param name="ccEmail"></param>
        /// <returns></returns>
        public async Task SendEmailAsync(string server ,int port ,string from ,List<string> toEmail, string subject, string message,string[] ccEmail)
        {
            MailMessage msg = new MailMessage();
            msg.From = new MailAddress(from, "automail", System.Text.Encoding.UTF8);
            foreach (var e in toEmail)
            {
                msg.To.Add(e);
            }
            /* 上面3个参数分别是发件人地址（可以随便写），发件人姓名，编码*/
            msg.Subject = subject;//邮件标题  
            foreach (var cc in ccEmail)
            {
                msg.CC.Add(cc); //抄送
            }
            msg.Body = message;
            msg.IsBodyHtml = true;//html格式发送
            msg.SubjectEncoding = System.Text.Encoding.UTF8;//邮件标题编码  

            using (var client = new SmtpClient() { Host = server, Port = port })
            {
                try
                {
                    client.Timeout = 10000; //超时
                    client.UseDefaultCredentials = true;
                    
                    //指定发送方式 
                    client.DeliveryMethod = SmtpDeliveryMethod.Network;
                    //指定登录名和密码 
                    client.Credentials = new System.Net.NetworkCredential("", "");
                    client.Send(msg);
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
    }
}
